<template>
  <view>
    <sanshuiModal ref="ssModal" :mode="_parentMode" :position="_parentPosition" @change="changeModal">
      <view class="digital-keyboard-modal" :class="'digital-keyboard-modal-' + _mode">
        <view class="dk-close" v-if="_mode !== 1 && _mode !== 4 && showClose" @click="close()"><icon type="clear" color="#333" :size="u50"></icon></view>
        <swiper class="dk-swiper" :current="current">
          <swiper-item @touchmove.prevent.stop>
            <view class="dk-title">{{ _titleObj.title }}</view>
            <view class="dk-subtitle">{{ _titleObj.subTitle }}</view>
            <view class="pwd-box clearfix" @click="getKeyboard">
              <view class="pwd-text" v-for="(item, index) in _digits" :key="index" :data-index="index" :class="{ active: activeInput == index }">{{ payPassWord[index] }}</view>
            </view>
          </swiper-item>
          <!-- 设置新支付密码 -->
          <block v-if="_mode === 2 || _mode === 5">
            <swiper-item @touchmove.prevent.stop>
              <view class="dk-title">{{ _titleObj.twoTitle }}</view>
              <view class="dk-subtitle">{{ _titleObj.twoSubTitle }}</view>
              <view class="pwd-box clearfix" @click="getKeyboard">
                <view class="pwd-text" v-for="(item, index) in _digits" :key="index" :data-index="index" :class="{ active: activeInput == index }">{{ payPassWord[index] }}</view>
              </view>
            </swiper-item>
          </block>
          <!-- 修改支付密码 -->
          <block v-else-if="_mode === 3">
            <swiper-item @touchmove.prevent.stop>
              <view class="dk-title">{{ _titleObj.twoTitle }}</view>
              <view class="dk-subtitle">{{ _titleObj.twoSubTitle }}</view>
              <view class="pwd-box clearfix" @click="getKeyboard">
                <view class="pwd-text" v-for="(item, index) in _digits" :key="index" :data-index="index" :class="{ active: activeInput == index }">{{ payPassWord[index] }}</view>
              </view>
            </swiper-item>
            <swiper-item @touchmove.prevent.stop>
              <view class="dk-title">{{ _titleObj.threeTitle }}</view>
              <view class="dk-subtitle">{{ _titleObj.threeSubTitle }}</view>
              <view class="pwd-box clearfix" @click="getKeyboard">
                <view class="pwd-text" v-for="(item, index) in _digits" :key="index" :data-index="index" :class="{ active: activeInput == index }">{{ payPassWord[index] }}</view>
              </view>
            </swiper-item>
          </block>
        </swiper>
        <block v-if="_mode !== 1 && _mode !== 4">
          <view class="pwd-tips">提现密码为6位数字，用于提现、设置密保、添加银行卡等操作，可保障资金安全</view>
          <view class="pwd-tips pwd-tips-errot">{{ msgText }}</view>
        </block>
        <view class="pwd-forget"><text v-if="_forget && _mode === 1" @click="forgetPwd">忘记提现密码</text></view>
        <view class="digital-keyboard" :class="{ 'digital-keyboard-show': dkFlag || _mode === 1 || _mode === 4 }">
          <view class="dk-down" v-if="_mode !== 1 && _mode !== 4">
            <block v-if="showPrevText"><view class="dk-submit dk-return" @click="changeSwiper(-1)">上一步</view></block>
            <svg class="icon icon-down" aria-hidden="true" @click="getKeyboard"><use xlink:href="#icon-down"></use></svg>
            <block v-if="trigger === 'auto'"><view class="dk-submit" @click="submit(true)">完成</view></block>
          </view>
          <view class="digital-key-box clearfix">
            <view class="num" v-for="item in digitalList" :key="item" :class="{ 'no-num': item === '' || item === '-1' }" @click="getKeyNumber(item)">{{ item }}</view>
          </view>
        </view>
      </view>
    </sanshuiModal>
  </view>
</template>

<script>
/* 密码弹窗插件，请移步：https://ext.dcloud.net.cn/plugin?id=555 */
/* mode 的可选值
    1 支付密码校验（用于校验安全）
    2 设置支付密码（2步  输入=》确认输入）
    3 修改支付密码（3步 原支付密码=》输入=》确认输入）
    4 找回登录密码（同mode = 1一样，就怕后端校验接口不一样而额外添加的一个mode）
    5 重置支付密码（同mode = 2一样，2步  输入=》确认输入）
   */
//依赖的弹窗模块
import sanshuiModal from '../sanshui-modal/index.vue';
export default {
  components: {
    sanshuiModal
  },
  data() {
    return {
      activeInput: 0, //当前输入的下标
      digitalList: ['1', '2', '3', '4', '5', '6', '7', '8', '9', '', '0', '-1'], //键盘
      paymentPwd: '', //支付密码内容
      dkFlag: true, //支付密码键盘的显示与隐藏
      current: 0,
      paymentPwds: [], //上一次支付密码内容,历史支付密码,
      msgText: '',
      u50: uni.upx2px(50)
    };
  },
  props: {
    showClose: {
      //是否显示关闭按钮
      type: Boolean,
      default: true
    },
    isPhone: {
      //是否显示关闭按钮
      type: Boolean,
      default: false
    },
    value: {
      type: String,
      default: ''
    },
    digits: {
      type: [Number, String],
      default: 6
    },
    forget: {
      type: Boolean,
      default: true
    },
    /*
     *	可选值说明（这一个顺序最好不要改，跟当前步骤步进行有关系，自动提交要用到mode跟current的判断  是否要自动提交）
     *	1 支付密码校验（用于校验安全）
     *	2 设置支付密码（2步  输入=》确认输入）
     *	3 修改支付密码（3步 原支付密码=》输入=》确认输入）
     *	4 找回登录密码(同mode = 1一样，就怕后端校验接口不一样而额外添加的一个mode)
     *	5 重置支付密码
     */
    mode: {
      type: [Number, String],
      default: 1
    },
    /*
     *	可选值说明
     *	hand 手动
     *	auto 自动
     */
    trigger: {
      type: String,
      default: 'auto'
    },
    userName: {
      type: String,
      default: ''
    }
  },
  computed: {
    payPassWord() {
      var payPassWord = this.paymentPwd.split('') || [];
      payPassWord.fill('*');
      return payPassWord;
    },
    _forget() {
      return String(this.forget) === 'false' ? false : true;
    },
    _digits() {
      return isNaN(this.digits) ? 6 : parseInt(this.digits);
    },
    _mode() {
      if (isNaN(this.mode) || !this.mode) {
        return 1;
      }
      return +this.mode;
    },
    _titleObj() {
      // title twoTitle  输入密码提示信息
      // subTitle 输入密码子提示
      // twoSubTitle 第二步提示
      // threeSubTitle 第三步提示
      let arr = [
        {
          title: '输入提现密码',
          subTitle: '请输入提现密码'
        },
        {
          title: '请设置新密码,用于提现验证',
          twoTitle: '请再次输入,以确认密码',
          subTitle: '',
          twoSubTitle: '',
        },
        {
          title: '修改提现密码',
          twoTitle: '设置提现密码',
          threeTitle: '设置提现密码',
          subTitle: '请输入提现密码 以验证身份',
          twoSubTitle: '请设置新的提现密码',
          threeSubTitle: '请再次输入提现密码以确认'
        },
        {
          title: '输入提现密码',
          subTitle: '请输入提现密码'
        },
        {
          title: '重置提现密码',
          subTitle: '请输入提现密码',
          twoSubTitle: '请再次输入提现密码以确认'
        }
      ];
      return arr[this._mode - 1];
    },
    // 父级宽度
    _parentMode() {
      return this._mode === 1 || this._mode === 4 ? 'full' : 'cover';
    },
    // 父级定位
    _parentPosition() {
      return this._mode === 1 || this._mode === 4 ? 'bottom' : 'middle';
    },
    // 是否显示上一步
    showPrevText() {
      return this.current >= this._mode - 1 || (this._mode === 5 && this.current > 0) ? true : false;
    }
  },
  watch: {
    current(newVal, oldVal) {
      // console.log(newVal);
      uni.$emit('updateCurrent', this.current);
    },
    isCheck(newVal, oldVal) {
      console.log(newVal);
      this.isCheckSuccess = newVal;
    }
  },
  methods: {
    // 模态框显示或者关闭的回调
    changeModal(e) {
      // 返回是一个Boolean值
      if (e) {
        this.current = 0;
        this.dkFlag = true; //默认拉起键盘
      } else {
        this.dkFlag = false; //默认收起键盘
        this.clearAll();
      }
    },
    /*
      	pro可选址
      	show	显示
      	hide	隐藏
      	toggle	动态判断
      */
    modalFun(pro) {
      this.$refs.ssModal[pro]();
    },
    clear() {
      this.paymentPwd = '';
      this.activeInput = 0;
      this.paymentPwds.splice(this.current, 1);
    },
    clearAll() {
      this.paymentPwd = '';
      this.activeInput = 0;
      this.current = 0;
      this.paymentPwds = [];
    },
    showError(msg) {
      if (!msg) return (this.msgText = '');
      if (this._mode !== 1 && this._mode !== 4) {
        this.msgText = msg;
      } else {
        uni.showToast({
          title: msg
        });
      }
    },
    forgetPwd() {
      console.log('这里是忘记密码跳转逻辑');
    },
    cancel() {
      this.$emit('cancel');
    },
    close() {
      let tips = '';
      let _this = this;
      if (this._mode === 2) {
        tips = '您是否要放弃设置提现密码';
      } else if (this._mode === 5) {
        tips = '您是否要放弃重置提现密码';
      } else {
        tips = '您是否要放弃修改提现密码';
      }
      this.$util.showModal({
        title: '关闭提示',
        content: tips,
        // confirmText: '我再想想',
        // confirmColor: '#f02523',
        // cancelText: '关闭',
        success: res => {
          if (res.confirm) {
            this.modalFun('hide');
            this.cancel();
          }
        }
      });
      // #ifndef APP-PLUS
      // this.$util.showModal({
      //   title: '关闭提示',
      //   content: tips,
      //   // confirmText: '我再想想',
      //   // confirmColor: '#f02523',
      //   // cancelText: '关闭',
      //   success: res => {
      //     if (!res.confirm) {
      //       this.modalFun('hide');
      //       this.cancel();
      //     }
      //   }
      // });
      // #endif
      // #ifdef APP-PLUS
      // uni.getSystemInfo({
      //   success: function(res) {
      //     console.warn('设备型号', res);
      //     if (res.platform === 'ios') {
      //       plus.nativeUI.confirm(
      //         tips,
      //         e => {
      //           console.log(e);
      //           if (e.index == 0) {
      //             _this.cancel();
      //           }
      //         },
      //         {
      //           title: '提示',
      //           buttons: ['关闭', '我再想想']
      //         }
      //       );
      //     } else {
      //       plus.nativeUI.confirm(
      //         tips,
      //         e => {
      //           console.log(e);
      //           if (e.index == 1) {
      //             _this.cancel();
      //           }
      //         },
      //         {
      //           title: '提示',
      //           buttons: ['我再想想', '关闭']
      //         }
      //       );
      //     }
      //   }
      // });

      // #endif
    },
    submit(clickFlag) {
      //clickFlag主动点击
      if (this.trigger !== 'auto' && !clickFlag) return;
      // 直接点击完成按钮时 判断密码是否输入完整
      if (this.paymentPwd.length !== this._digits) {
        this.showError('请输入' + this._digits + '位提现密码');
      } else {
        this.showError('');
        if (this._mode === 5 || this._mode === 4 || this.current >= this._mode - 1) {
          if (this._mode === 5 && this.current === 0) {
            // 下一步，再次输入
            return this.changeSwiper(1);
          }
          if (this.current > 0) {
            // 需要校验2次支付密码的是否相等
            console.log(this.paymentPwd, this.paymentPwds[this.current - 1]);
            if (this.paymentPwd !== this.paymentPwds[this.current - 1]) {
              this.showError('两次提现密码输入不一致');
              this.paymentPwd = '';
              this.paymentPwds[this.current] = '';
              this.clear();
              return;
            }
            this.showError('');

            //手机辅助修改
            if(this.isPhone){
              this.$emit('submit', {
                type: 'modify',
                value: this.paymentPwd
              });
              return
            }


            if (this._mode === 2) {
              //设置支付密码
              uni.showLoading({
                title: '正在设置密码'
              });
              // 如果不把逻辑卸载这里面，直接把setTimeout删除即可
              // uni.hideLoading();
              this.$emit('submit', {
                //这里是传出去给调用者的，参数任意下，只要能区分就行
                type: 'reset',
                value: this.paymentPwd
              });
              // this.modalFun('hide');
            } else {
              //修改支付密码
              uni.showLoading({
                title: '正在重置密码'
              });
              // 如果不把逻辑卸载这里面，直接把setTimeout删除即可
              this.$emit('submit', {
                type: 'modify',
                value: this.paymentPwd
              });
              // this.modalFun('hide');
            }
            return;
          }
          this.checkSafePwd('check');
        } else {
          if (this._mode === 3 && this.current === 0) {
            //校验支付密码正确性
            this.checkSafePwd('verify');
            return;
          }
          this.changeSwiper(1);
        }
      }
    },
    async checkSafePwd(type) {
      console.log(type);
      if (type == 'verify') {
        // 输出验证
        // #ifdef H5
        const res = await this.$parent.$parent.checkPayPwd(this.paymentPwd);
        // #endif
        // #ifndef H5
        const res = await this.$parent.checkPayPwd(this.paymentPwd);
        // #endif
        console.log(res)
        if(res.data.code == 1){
          // #ifdef H5
          this.$parent.$parent.pay_password = this.paymentPwd;
          // #endif
          // #ifndef H5
          this.$parent.pay_password = this.paymentPwd;
          // #endif
          // 执行下一步
          this.changeSwiper(1);
        }else{
          this.msgText = res.data.msg;
          this.paymentPwd = '';
        }
        return;
      }
      if (type === 'check') {
        this.$emit('submit', {
          //设置或者重置新支付密码
          type: 'check',
          value: this.paymentPwd
        });
        this.modalFun('hide');
      } else {
        this.changeSwiper(1); //执行下一步
      }

      // setTimeout(() => {//模拟请求，把这个换成ajax请求哈，或者emit出去 外面去请求，但是建议都集成在这边 省的写一堆重置代码
      // 	uni.hideLoading();
      // 	let response = {//模拟返回
      // 		code: 1,
      // 		msg: '密码正确'
      // 	}
      // 	if(response.code === 1){
      // 		if(type === 'check'){
      // 			this.$emit('submit', {//设置或者重置新支付密码
      // 				type: 'check',
      // 				value: this.paymentPwd
      // 			});
      // 			this.modalFun('hide');
      // 		}else{
      // 			this.changeSwiper(1);//执行下一步
      // 		}
      // 	}else{
      // 		this.clear();
      // 		if(type !== 'check'){
      // 			this.showError(response.msg);
      // 		}
      // 	}
      // }, 1000)
    },
    changeSwiper(num) {
      if (isNaN(num)) {
        num = 1;
      }
      this.current += num;
      this.paymentPwd = this.paymentPwds[this.current] || '';
      if (this.paymentPwd.length == 0) {
        this.activeInput = 0;
      } else {
        this.activeInput = this.paymentPwd.length - 1;
      }
    },
    getKeyNumber(val) {
		console.log(val)
      let paymentPwdArr = this.paymentPwd.split('');
      // val为空值是点击了键盘左下角的空值方格 或则val与设置密码长度一致时  this._digits且是自动跳转时走完成事件
      if (val === '' || (val != -1 && paymentPwdArr.length === this._digits)) {
        //空或者已经达到最大值
        if (paymentPwdArr.length === this._digits && this.trigger === 'auto') {
          this.submit();
          return;
        }
        return false;
      } else if (val != -1) {
        // val不为空时证明正在输入
        //数字输入 this.activeInput光标在第几个位置就在第几个位置插入
        paymentPwdArr.splice(this.activeInput, 0, val);
        this.activeInput++;
        this.paymentPwd = paymentPwdArr.join('');
        // 三步走的第几个密码框输入值
        this.paymentPwds[this.current] = this.paymentPwd;
        // 当密码长度已满且自动跳转时
        if (paymentPwdArr.length === this._digits && this.trigger === 'auto') {
          this.submit();
          return;
        }
      } else {
        // 点击了删除按钮
        //删除
        if (this.activeInput >= 0) {
          this.activeInput !== 0 && this.activeInput--;
          // 删除一位已经输入的密码  光标在哪从哪里删除
          paymentPwdArr.splice(this.activeInput - 1, 1);
          this.paymentPwd = paymentPwdArr.join('');
          this.paymentPwds[this.current] = this.paymentPwd;
        }
      }
    },
    getKeyboard(e) {
      let index = e && e.target.dataset.index;
      if (index === undefined) {
        this.activeInput = -1;
        this.dkFlag = false;
        return;
      }
      var _length = this.paymentPwd.length;
      this.activeInput = index <= _length ? index : _length;
      this.dkFlag = true;
    }
  },
  onLoad() {
    uni.$on('isStep', data => {
      console.log(data);
      this.isSuccess = data;
    });
  }
};
</script>

<style lang="scss">
.digital-keyboard-modal {
  height: 100%;
  background-color: #fff;

  &.digital-keyboard-modal-1,
  &.digital-keyboard-modal-4 {
    height: auto;
    border-radius: 20px 20px 0px 0px;
    background: #fff
      url()
      center top / 100% auto no-repeat;
    padding-padding: 0;
    padding-padding: constant(safe-area-inset-top);
    padding-padding: env(safe-area-inset-top);
  }

  &.digital-keyboard-modal-2,
  &.digital-keyboard-modal-5,
  &.digital-keyboard-modal-3 {
    padding-top: calc(var(--status-bar-height) + 180rpx);

    .dk-title {
      color: #000;
    }

    .digital-keyboard {
      width: 100%;
      position: fixed;
      bottom: 0;
      left: 0;
      position: fixed;
      left: 0;
      bottom: 0;
    }
  }

  .dk-title {
    font-size: 36rpx;
    font-weight: 800;
    color: #fff;
    line-height: 90rpx;
    text-align: center;
  }

  .dk-swiper {
    height: 260rpx;
  }

  .dk-submit {
    position: absolute;
    right: 0;
    top: 0;
    padding: 0 20rpx;
    color: $fu-main-color;
    font-size: 28rpx;
    line-height: 70rpx;
  }

  .dk-return {
    right: auto;
    left: 0;
  }

  .dk-close {
    position: fixed;
    left: 30rpx;
    top: calc(var(--status-bar-height) + 30rpx);
  }

  .dk-subtitle {
    height: 60rpx;
    font-size: 24rpx;
    color: #2999f8;
    text-align: center;
  }

  .dk-down {
    text-align: center;
    line-height: 70rpx;
    box-shadow: 0 0 0 2rpx #eee;

    .icon {
      width: 40rpx;
      height: 40rpx;
    }
  }

  .pwd-tips {
    color: #666;
    font-size: 24rpx;
    line-height: 1.5;
    padding: 15rpx 100rpx;
  }

  .pwd-tips-errot {
    color: #ff4242;
    font-size: 30rpx;
    text-align: center;
  }

  .pwd-forget {
    font-size: 24rpx;
    color: #26c6b3;
    padding: 20rpx 0 30rpx;
    text-align: center;
    line-height: 33rpx;
  }

  .digital-keyboard {
    box-shadow: 0 -1rpx 0 3rpx #eee;
    width: 100%;
    transition: all 0.2s linear;
    transform: translateY(100%);
  }

  /* 键盘 */
  .digital-key-box {
    box-shadow: 0 0 0 2rpx #eee;
    position: relative;
    overflow: hidden;
    width: 100%;
  }

  .digital-keyboard-show {
    transform: translateY(0);
  }

  .num {
    transition: all 0.2s linear;
    float: left;
    background-color: #fff;
    box-shadow: 0 0 0 2rpx #eee;
    width: 33.33333333%;
    cursor: pointer;
    height: 100rpx;
    text-align: center;
    color: #333;
    line-height: 100rpx;
    font-size: 55rpx;
    font-weight: bold;
    position: relative;
    overflow: hidden;

    &:after {
      content: '';
      display: block;
      position: absolute;
      width: 100%;
      height: 100%;
      top: 0;
      left: 0;
      pointer-events: none;
      //设置径向渐变
      background-image: radial-gradient(circle, rgba(0, 0, 0, 0.65) 20%, transparent 20%);
      background-repeat: no-repeat;
      background-position: 50%;
      transform: scale(5);
      opacity: 0;
      transition: transform 0.2s ease-in-out, opacity 0.3s ease-in-out;
    }

    &:active:after {
      transform: scale(0);
      opacity: 0.5;
      //设置初始状态
      transition: 0s;
    }
  }

  .num:nth-of-type(3n + 1) {
    border-bottom: 0;
    border-left: 0;
  }

  .num:nth-of-type(3n + 2) {
    border-bottom: 0;
    border-left: 0;
    border-right: 0;
  }

  .num.no-num {
    background-color: #f2f2f2;
    font-size: 0;
  }

  .num:last-child {
    background: #f2f2f2
      url()
      center center / auto 50rpx no-repeat;
  }

  .pwd-box {
    padding-left: 10rpx;
    position: relative;
    text-align: center;
  }

  .pwd-text {
    position: relative;
    line-height: 110rpx;
    vertical-align: middle;
    text-align: center;
    font-size: 50rpx;
    font-weight: bold;
    width: 92rpx;
    height: 92rpx;
    // margin-right: 10rpx;
    display: inline-block;
    box-shadow: 0 0 0 2rpx #ccc;
    overflow: hidden;
  }

  .pwd-text.active:after {
    -webkit-animation: twinkle 1s infinite;
    animation: twinkle 1s infinite;
    height: 70%;
    width: 4rpx;
    content: '';
    position: absolute;
    top: 15%;
    left: 50%;
    margin-left: -2rpx;
    background-color: $fu-main-color;
  }

  @keyframes twinkle {
    from {
      background-color: $fu-main-color;
    }

    to {
      background-color: transparent;
    }
  }
}
</style>
